import gradio as gr
from debate_controller_backup import DebateController
import time

def create_ui():
    js = """
                () => {
                    setInterval(() => {
                        const chatbot = document.querySelector('.gradio-chatbot');
                        if(chatbot) {
                            chatbot.scrollTop = chatbot.scrollHeight;
                        }
                    }, 100);
                }
                """
    with gr.Blocks(js=js) as demo:
        chatbot = gr.Chatbot(type="messages", height=800)
        status = gr.Textbox(label="状态", value="准备就绪")
        start_btn = gr.Button("开始辩论")

        def debate_generator(history: list):
            controller = DebateController("中学生是否应该带手机进入校园")
            previous_speaker = None
            current_role = "assistant"  # 初始角色
            try:
                for speaker, message in controller.run_debate():
                    current_role = "user" if current_role == "assistant" else "assistant"
                    previous_speaker = speaker
                    history.append({"role": current_role, "content": ""})

                    for character in message:
                        history[-1]['content'] += character
                        time.sleep(0.05)
                        # yield history
                        yield history, f"{speaker} 正在发言..."

                yield history, "辩论已结束"
            except Exception as e:
                yield history, f"发生错误: {str(e)}"

        start_btn.click(
            fn=debate_generator,
            inputs=chatbot,
            outputs=[chatbot, status],
            show_progress="hidden"
        )

    return demo


if __name__ == "__main__":
    ui = create_ui()
    ui.launch()
